package org.example.shop_front_api.controller;

import org.example.shop_front_api.entity.ESNews;
import org.example.shop_front_api.utils.JsonResult;
import org.example.shop_front_api.utils.Tool;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.elasticsearch.client.elc.NativeQuery;
import org.springframework.data.elasticsearch.client.elc.NativeQueryBuilder;
import org.springframework.data.elasticsearch.core.ElasticsearchOperations;
import org.springframework.data.elasticsearch.core.IndexOperations;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.query.Criteria;
import org.springframework.data.elasticsearch.core.query.CriteriaQuery;
import org.springframework.data.elasticsearch.core.query.HighlightQuery;
import org.springframework.data.elasticsearch.core.query.highlight.Highlight;
import org.springframework.data.elasticsearch.core.query.highlight.HighlightField;
import org.springframework.data.elasticsearch.core.query.highlight.HighlightParameters;
import org.springframework.web.bind.annotation.*;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("api/news")
public class EsNewsController {
    @Autowired
    private ElasticsearchOperations elasticsearchOperations;
    //创建索引
    @GetMapping("create")
    public JsonResult create() {
        IndexOperations indexOperations = elasticsearchOperations.indexOps(ESNews.class);
        if (!indexOperations.exists()) {
            indexOperations.create();
        }
        return JsonResult.success("ok",null);
    }

    //索引文档
    @PostMapping("add")
    public JsonResult add(@RequestBody ESNews news) {
        news.setCreateTime(Tool.getCurrentTime());
        System.out.println(news);
        ESNews result = elasticsearchOperations.save(news);
        return JsonResult.success("添加成功",news);
    }
    //删除文档
    @GetMapping("delete")
    public JsonResult delete(@RequestParam("id") String id) {
        if (id.isEmpty()) {
            return JsonResult.failed("id不能为空");
        }
        String result = elasticsearchOperations.delete(id, ESNews.class);
        return JsonResult.success("删除成功",null);
    }

    //精确搜索
    @GetMapping("search")
    public JsonResult search(@RequestParam("wd") String wd) {
        if (wd.isEmpty()) {
            //
        }
        System.out.println(wd);
        Criteria criteria = new Criteria("title").contains(wd);
        CriteriaQuery query = new CriteriaQuery(criteria);

        SearchHits<ESNews> hits = elasticsearchOperations.search(query, ESNews.class);
        System.out.println(hits);

        List<ESNews> newsList = hits.stream()
                .map(SearchHit::getContent)
                .toList();
        return JsonResult.success("ok",newsList);
    }
    //ik分词搜索
    @GetMapping("match")
    public JsonResult match(@RequestParam("wd") String wd) {
        NativeQuery query = NativeQuery.builder()
                .withQuery(q -> q
                        .match(m -> m
                                .field("title")
                                .query(wd)
                        )
                )
                .build();

        SearchHits<ESNews> searchHits = elasticsearchOperations.search(query, ESNews.class);
        HashMap<String, Object> resultData = new HashMap<>();
        resultData.put("hits", searchHits.getSearchHits());
        resultData.put("totalHits", searchHits.getTotalHits());
        return JsonResult.success("搜索成功",resultData);
    }

    // 高亮搜索
    @GetMapping("highlight")
    public JsonResult highlight(@RequestParam("wd") String wd) {
        // 创建高亮配置
        HighlightField highlightField = new HighlightField("title");
        HighlightParameters parameters = HighlightParameters.builder()
                .withPreTags("<span style='color: red'>")
                .withPostTags("</span>")
                .withFragmentSize(Integer.MAX_VALUE)
                .withNumberOfFragments(1)
                .build();


        Highlight highlight = new Highlight(parameters, List.of(highlightField));
        HighlightQuery highlightQuery = new HighlightQuery(highlight, ESNews.class);

        // 构建查询
        NativeQuery query = NativeQuery.builder()
                .withQuery(q -> q
                        .match(m -> m
                                .field("title")
                                .query(wd)
                        )
                ).withPageable(
                        PageRequest.of(0, 10,
                                Sort.by(
                                        Sort.Order.desc("create_time")
                                )
                        )
                )
                .withHighlightQuery(highlightQuery)
                .build();
        SearchHits<ESNews> searchHits = elasticsearchOperations.search(query, ESNews.class);
        HashMap<String, Object> resultData = new HashMap<>();
        resultData.put("hits", searchHits.getSearchHits());
        resultData.put("totalHits", searchHits.getTotalHits());
        return JsonResult.success("搜索成功",resultData);
    }

    @GetMapping("muli_match")
    public JsonResult muliMatch(@RequestParam("wd") String wd) {

        // 1. 构建多字段查询 + 高亮配置
        NativeQuery query = new NativeQueryBuilder()
                // 多字段匹配查询
                .withQuery(q -> q.multiMatch(m -> m
                        .query(wd) // 搜索关键词
                        .fields("title^3", "content") // 匹配字段，title 权重更高
                ))
                .build();

        // 2. 执行查询
        SearchHits<ESNews> hits = elasticsearchOperations.search(query, ESNews.class);
        List<ESNews> result = hits.stream()
                .map(SearchHit::getContent)
                .collect(Collectors.toList());
        return JsonResult.success("ok",result);
    }

}
